/*
 * Creator:     ML
 * CreatDate:   2019-12-19
 * descripts：  医嘱查询--查找(住院) 药品
 * */
import React from 'react';
import { Form, Button, Table, message, Select } from 'antd';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import { $http } from 'containers/config/https';
import { Util } from 'tools/index';
import store from 'store';
import moment from 'moment';
import fetchJsonp from 'fetch-jsonp';
// import CommonPagination from 'components/pagination/index';
import ViewInsReportTarget from 'pages/workstation/component/ViewInsReportTarget';
import OrdersModel from "pages/nurse/orders/ordersModel";
import RangeDatePicker from 'components/rangePicker/index';
import { dayFormat } from 'tools/index';

class HospitaDoctorAdviceFind extends React.Component {
  constructor(props) {
    super(props)
    var date = new Date();
    var userData = JSON.parse(sessionStorage.getItem('userData'));
    this.state = {
      userData: userData,
      loading: false,
      visible: false,
      total: 0,//表格总数据
      consuilationData: [],//查询出来的检查报告数据
      values: {},//查询条件数据
      searchLoading: false,//查询请求
      rowIds: '',//表格行选中 页面数据
      columns: [],//检查报告表头
      widthTotal: 0,//宽
      columnsVisible: false,//配置表头显隐
      page: 1,
      pageSize: 10,
      starNoVisible: false,
      startNoMessage: "",
      search: "",
      size: "small",
      startDate: moment().subtract(1, 'months').format(dayFormat),  // //开始日期
      endDate: moment(date).format(dayFormat),  // //结束日期
    }
  }

  componentDidMount() {
    if (document.querySelector('.ant-table-body')) {
      if (this.props && this.props.modal) {
        //放置在弹窗上
        document.querySelector(".reportDom .ant-table-body").style.height = store.getState().tableHeight.y - 136 + 'px';
        document.querySelector(".reportDom .ant-table-body").style.maxHeight = store.getState().tableHeight.y - 136 + 'px';
      } else {
        //放置在普通页面上
        document.querySelector(".reportDom .ant-table-body").style.height = store.getState().tableHeight.y - 182 + 'px';
        document.querySelector(".reportDom .ant-table-body").style.maxHeight = store.getState().tableHeight.y - 182 + 'px';
      }

    }
    this.getMainTableColumns()
    setTimeout(() => {
      this.getFindDate("search");
    }, 600)
  }

  onColumnRef = (ref) => {
    this.columnRef = ref;
  }

  Onres = (ref) => {
    this.childs = ref
  }

  handleOpen = (e, url) => {
    this.childs.showModals(url)
  }

  //调起本地服务 --imgUrl
  handleOpenImg = (e, url) => {
    if (url && url.length > 0) {
      let address = 'path:"C:/ProgramData/XYS/XYSService/plugins/PacsRead/",';
      let param = url.replace(/\&/g, "%26");
      let inputObj = '{ inputDir:"PacsRead/OpenExe.dll", clsName:"OpenExe.ExeObj",funcName:"CreateProcess",dllInput:{' + address + 'exeName:"OpenPacs.exe",parameter:"' + param + '"}}';
      fetchJsonp('http://127.0.0.1:62534/XYSWCFService/DynamicLoadingDLL?input=' + inputObj)
        .then(res => res.json())
      // .then(data =>
      //    console.log(data));
    } else {
      message.warning("该检查科室没有配置报告样式文件，请与系统管理员联系!")
    }
  }

  onRefsLift = (ref) => {
    this.childRefLift = ref
  }

  handleOpenLife = (e, ordID) => {
    this.childRefLift.showModal(ordID)
  }

  // 获取主列表columns
  getMainTableColumns = () => {
    /**
    * @ByShizi: 走药品维护列表
    * Create 2021-03-25
    * */
    let data = {
      params: [{
        compontName: "HospitaDoctorAdviceFind",
        reactCode: ['HospitaDoctorAdviceFind'],
        type: 'C', // 卡类型id
      }]
    }
    $http.post('urlS', this, {
      code: '01040073',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          let arr = res.result && res.result.C.length > 0 ? JSON.parse(JSON.stringify(res.result.C)).map(item => {
            return {
              align: item.align,
              widthNum: parseInt(item.width),
              width: item.width,
              dataIndex: item.dataIndex,
              title: <div onDoubleClick={() => this.columnRef.onOpenModel()}>{this.state.userData.language == 'EN' ? item.descripts : item.title}</div>,
              display: item.display,
              key: item.seqNo,
              render: (text, record) => {
                if (item.code == "ordStatusDesc") {
                  return (
                    <span style={{ color: text === '作废' ? 'red' : 'rgba(0, 0, 0, 0.65)' }}>{text}</span>
                  )
                }
                return text
              }
            }
          }) : '';
          let filterArr = arr.filter(function (item) { return item.display === 'Y' });
          // console.log("filterArr",filterArr)
          this.setState({ localeProvider: this.state.userData.language == 'EN' ? res.result.language.EN : res.result.language.CN, columns: filterArr, widthTotal: parseInt(res.totalWidth) })
        }
      }
    })
  }

  //国际化
  setMessage(name, message) {
    return this.state.localeProvider ? this.state.localeProvider[name][message] : ''
  }

  // 修改page和pageSize 跳转至---
  onChange = (page, pageSize) => {
    this.setState({ page: page, pageSize: this.state.pageSize }, () => {
      // 重新调用查询方法
      this.getFindDate();
    })
  }

  //下拉选择页数
  onShowSizeChange = (page, pageSize) => {
    this.setState({ page: 1, pageSize: pageSize }, () => {
      // 重新调用查询方法
      if (this.state.consuilationData && this.state.consuilationData.length > 0) {
        this.getFindDate("search");
      }
    })
  }

  // 显示分页总条数
  showTotal(total) {
    return `共 ${total} 条`;
  }

  //获取查询数据
  getFindDate = (e) => {
    const { startDate, endDate } = this.state;
    if (this.state.total == 0) {
      this.setState({
        searchLoading: true
      })
    }
    let { page, pageSize, } = this.state;
    let data = {}
    data = {
      params: [{
        patID: this.props && this.props.patID ? this.props.patID : sessionStorage.patientData ? JSON.parse(sessionStorage.patientData).patID : "",
        admID: this.props && this.props.admID ? this.props.admID : sessionStorage.patientData ? JSON.parse(sessionStorage.patientData).admID : "",
        fromDate: startDate,//开始日期
        toDate: endDate,//截止日期
      }],
      pagination: [{
        pageSize: pageSize,
        currentPage: page,
      }]
    }
    $http.post('urlS', this, {
      code: '03050268',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          let consuilationData = res.result && 'data' in res.result ? Util.addKeyValueToDataSource(res.result.data) : Util.addKeyValueToDataSource(res.result);
          let total = 'totalCount' in res && res.totalCount ? res.totalCount : consuilationData?.length;
          this.setState({
            searchLoading: false,
            rowId: "",
          })
          this.setState({ consuilationData, search: e, total }, () => {
          })
        } else {
          this.setState({
            searchLoading: false
          })
        }
      },
      error: function () {
        this.setState({
          searchLoading: false
        })
      }
    })
  }

  //--检查报告列表
  findDatas = () => {
    this.setState({
      rowIds: ""
    })
    this.setState({ page: 1, pageSize: this.state.pageSize }, () => {
      this.getFindDate("search")
    })
  }

  handleCancel = () => {
    this.handleRest()
    this.setState({
      visible: false,
      bindMoreInfo: false,
      bindVail: true
    });
  }

  //隐藏提示信息
  visibleTip = () => {
    this.setState({
      starNoVisible: false,
    })
  }

  onRefs = (ref) => {
    this.child = ref
  }

  //开始日期
  startChange(date) {
    this.setState({
      startDate: date,
    })
  }

  //结束日期
  endChange(date) {
    this.setState({
      endDate: date,
    })
  }

  render() {
    const { searchLoading, widthTotal, columns } = this.state;

    return (
      <div className="reportDom">
        <div className="testResultDom flex-align-items" style={{ margin: "12px" }}>
          <RangeDatePicker isChange={true} label={this.state.userData.language == 'EN' ? '	Medical date：' : '医嘱日期：'} format='YYYY-MM-DD' width={300}
            startDate={this.state.startDate} endDate={this.state.endDate}
            startChange={this.startChange.bind(this)} endChange={this.endChange.bind(this)} />
          <Button onClick={this.findDatas} loading={searchLoading} style={{ background: 'rgba(66,185,131,1)', color: '#fff', marginLeft: '12px' }}>
            {this.state.localeProvider && this.state.localeProvider.ExamineReportSearch ? this.setMessage('ExamineReportSearch', 'descripts') : "查询"}
          </Button>
        </div>
        <Table
          scroll={{ x: (columns && columns.length > 0 ? widthTotal : 4000), y: store.getState().tableHeight.y + 51 }}
          columns={columns && columns.length > 0 ? columns : []}
          dataSource={this.state.consuilationData}
          pagination={false}
          rowKey={record => record.key}
          bordered
          style={{ height: this.props && this.props.modal ? store.getState().tableHeight.y - 82 + 'px' : store.getState().tableHeight.y - 133 + 'px', overflow: "auto" }}
        />
        {/* <CommonPagination size={this.state.size} current={this.state.page} total={this.state.total} search={this.state.search}
          onShowSizeChange={this.onShowSizeChange.bind(this)} complete={true} dataSource={this.state.consuilationData}
          onChange={this.onChange.bind(this)} /> */}
        <ColumnAuthoritysModel
          clientWidth='800px'
          compontName='ExamineReport'
          configType="C"
          onRef={this.onColumnRef}
          reloadData={this.getMainTableColumns}
        />
        <ViewInsReportTarget Onres={this.Onres}></ViewInsReportTarget>
        <OrdersModel onRefs={this.onRefsLift}></OrdersModel>
      </div>
    )
  }
};

export default Form.create()(HospitaDoctorAdviceFind);